package com.bootnetty.utils;

import com.bootnetty.entity.Result;
import com.bootnetty.entity.Sensors;
import com.bootnetty.entity.Station;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * Created by stevenfenCai on 2019-11-12.
 */
public class CommandUtils {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 组合反馈指令
     *
     * @param result
     * @return
     */
    public static String[] codeCommand(Result result) {
        String[] commands = new String[result.getIDs().size()];
        for (int i = 0; i < result.getIDs().size(); i++) {
            String command = "";
            //组合数据模块
            String data = "";
            data += result.getIDs().get(i);
            data += result.getModes().get(i);
            data += result.getExpectTemperature().get(i);
            data += result.getExpectHumidity().get(i);


            String UTC = StringUtils.reverse(String.format("%08x", new Date().getTime() / 1000));
            String CRCPath = result.getDataID() + UTC + result.getPid() + result.getDataType() + data;
            String CRC = StringUtils.getCrc(StringUtils.hexStr2Byte(CRCPath));
            String mainPath = CRC + CRCPath;

            String head = StringUtils.reverse(String.format("%04x", mainPath.length() / 2));
            command = (command + head + mainPath).toUpperCase();
            commands[i] = command;
        }
        return commands;
    }

    /**
     * 消息解码
     * @param message
     * @return
     */
    public static Map<String,Object> decodeCommand(String message) {
        if (message.length() > 0 && StringUtils.verificate(message)) {

            Map<String,Object> map = new HashMap<String,Object>();
            //发送帧 ID
            String sendID = message.substring(8, 16);
            Date time = StringUtils.transForDate(Long.parseLong(StringUtils.reverse(message.substring(16, 24)), 16) * 1000);
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime = sdf.format(time);

            //发送组件 ID
            String pidSerialNumStr = message.substring(24, 40);
            Long pidSerialNum = Long.parseLong(StringUtils.reverse(pidSerialNumStr), 16);
            //数据类型 0
            String dataType = message.substring(40, 44);
            Integer dataLength = StringUtils.StrtransInt(StringUtils.reverse(message.substring(44, 48)));

            Result result = DBUtils.getStationConfig(pidSerialNum);
            result.setDataID(sendID);
            result.setPid(pidSerialNumStr);
            result.setDataType(dataType);
            String[] sendMessage = codeCommand(result);


            List<Sensors> sensorsList = new ArrayList<>();
            List<Station> stationList = new ArrayList<>();
            for (int i = 0; i < dataLength; i++) {
                //获取单个数据
                String data = message.substring(48 + i * 40, 48 + (i + 1) * 40);
                Long ID = 0L;
                if (pidSerialNum.equals(4311744512L)) {
                    ID = Long.parseLong(StringUtils.reverse(data.substring(0, 16)), 16);
                } else {
                    ID = Long.parseLong(data.substring(4, 16), 16);
                }
                System.out.println(data.substring(4, 16));
                Integer Mode = Integer.parseInt(data.substring(17, 18), 16);
                String ModeStr = StringUtils.toBinaryString(Mode);
                Integer TMode = Integer.parseInt(ModeStr.substring(3, 4)) == 0 ? 78 : 79;
                Integer HMode = Integer.parseInt(ModeStr.substring(2, 3)) == 0 ? 78 : 79;
                Integer TSatus = Integer.parseInt(ModeStr.substring(1, 2)) == 0 ? 76 : 77;
                Integer HSatus = Integer.parseInt(ModeStr.substring(0, 1)) == 0 ? 76 : 77;

                Double expectTemperature = Integer.parseInt(data.substring(20, 24), 16) / 100.0;
                Double expectHumidity = Integer.parseInt(data.substring(24, 28), 16) / 100.0;
                Integer active = Integer.parseInt(StringUtils.reverse(data.substring(28, 32)), 16) > 0 ? 0 : 1;
                Double temperature = Integer.parseInt(data.substring(32, 36), 16) / 100.0;
                Double humidity = Integer.parseInt(data.substring(36, 40), 16) / 100.0;
                if (pidSerialNum.equals(4311744512L)) {
                    expectTemperature = Integer.parseInt(StringUtils.reverse(data.substring(20, 24)), 16) / 10.0;
                    expectHumidity = Integer.parseInt(StringUtils.reverse(data.substring(24, 28)), 16) / 10.0;
                    temperature = Integer.parseInt(StringUtils.reverse(data.substring(32, 36)), 16) / 10.0;
                    humidity = Integer.parseInt(StringUtils.reverse(data.substring(36, 40)), 16) / 10.0;
                }
                Sensors sensors = new Sensors();
                sensors.setDeleted(0);
                sensors.setCreateDate(currentTime);
                sensors.setUpdateDate(currentTime);
                sensors.setTS(currentTime);
                sensors.setTemperature(temperature);
                sensors.setHumidity(humidity);
                sensors.setTMode(TMode);
                sensors.setHMode(HMode);
                sensors.setSerialNum(ID);
                sensorsList.add(sensors);


                Station station = new Station();
                station.setHMode(HMode);
                station.setTMode(TMode);
                station.setSerialNum(ID);
                station.setHSatus(HSatus);
                station.setTSatus(TSatus);
                station.setActive(active);
                station.setExpectTemperature(expectTemperature);
                station.setExpectHumidity(expectHumidity);
                stationList.add(station);
            }

            map.put("sensorsList",sensorsList);
            map.put("stationList",stationList);
            return map;
        }
        return null;
    }
}
